package com.sample.base.http

import com.google.gson.Gson
import okhttp3.*
import java.io.IOException
import java.lang.reflect.Type

/**
 *  @Author Created by Z on 2020/4/15 星期三 17:31
 *  @Desc :
 */
class HttpClient private constructor() : OkHttpClient() {
  companion object {
    fun getInstance(): HttpClient {
      return Holder.INSTANCE
    }
  }

  private object Holder {
    val INSTANCE = HttpClient()
  }


  val gson = Gson()

  private fun <T> convert(json: String, type: Type): T {
    return gson.fromJson(json, type)
  }

  fun <T> get(path: String, type: Type, callback: EntityCallback<T>) {
    val request = Request.Builder()
      .url("https://api.hencoder.com/$path")
      .build()
    val call = getInstance().newCall(request)
    call.enqueue(object : Callback {
      override fun onResponse(call: Call, response: Response) {
        when (response.code()) {
          in 200..299 -> {
            callback.onSuccess(convert(response.body().toString(), type) as T)
          }
          in 400..499 -> {
            callback.onFailure("客户端错误")
          }
          in 501..599 -> {
            callback.onFailure("服务器错误")
          }
          else -> {
            callback.onFailure("未知错误")
          }
        }

      }

      override fun onFailure(call: Call, e: IOException) {
        callback.onFailure("发生异常")
      }
    })
  }

}